﻿using BingSpatialDataServiceExcelAddin.BSDSTools.Models;
using System;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.Linq;
using System.Collections.Generic;

namespace BingSpatialDataServiceExcelAddin.Views
{
    public partial class DataSourceManager : UserControl
    {
        public DataSourceManager()
        {
            InitializeComponent();

            Settings settings = new Settings(Globals.ThisAddIn.Application.ActiveWorkbook);
            BingMapsKeyTbx.Text = settings.MasterKey;
        }

        private void GetInfoBtn_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrWhiteSpace(BingMapsKeyTbx.Text)){
                MessageBox.Show("Invalid Bing Maps Key provided.");
                return;
            }

            try
            {
                this.DataSourceListBox.DataContext = null;
                ResultsLbl.Text = string.Empty;

                WebClient wc = new WebClient();
                using (Stream stream = wc.OpenRead("https://spatial.virtualearth.net/REST/v1/data?$format=atom&key=" + BingMapsKeyTbx.Text))
                {
                    IList<DataSourceInfo> dataSources = new List<DataSourceInfo>();

                    XDocument xmlDoc = XDocument.Load(stream);
                    DateTime dt;
                    bool b;

                    foreach (XElement element in xmlDoc.Descendants(Constants.NameSpaces.app + "workspace"))
                    {
                        DataSourceInfo ds = new DataSourceInfo();

                        if (element.HasAttributes)
                        {
                            if(DateTime.TryParse(element.Attribute(Constants.NameSpaces.bsi + "updated").Value, out dt)){
                                ds.Updated = dt;
                            }

                            if (bool.TryParse(element.Attribute(Constants.NameSpaces.bsi + "isPublic").Value, out b))
                            {
                                ds.IsPublic = b;
                            }
                        }

                        ds.Name = element.Element(Constants.NameSpaces.atom + "title").Value;

                        XElement xCollection = element.Element(Constants.NameSpaces.app + "collection");

                        if (xCollection != null)
                        {
                            if (xCollection.HasAttributes)
                            {
                                ds.QueryURL = xCollection.Attribute(Constants.NameSpaces.app + "href").Value;
                            }

                            ds.EntityType = xCollection.Element(Constants.NameSpaces.atom + "title").Value;
                        }

                        dataSources.Add(ds);
                    }

                    if (dataSources.Count > 0)
                    {
                        this.DataSourceListBox.DataContext = dataSources;
                        ResultsLbl.Text = string.Format("Found {0} data sources.", dataSources.Count);
                    }
                    else
                    {
                        this.DataSourceListBox.DataContext = null;
                        ResultsLbl.Text = "No data source information found.";
                    }
                }
            }
            catch (Exception ex){
                MessageBox.Show("Error: " + ex.Message);
            }
        }

        private void GetJobsBtn_Click(object sender, EventArgs e)
        {
            this.DataSourceJobListBox.DataContext = null;

            if(string.IsNullOrWhiteSpace(BingMapsKeyTbx.Text)){
                MessageBox.Show("Invalid Bing Maps Key provided.");
                return;
            }

            try
            {
                WebClient wc = new WebClient();
                wc.OpenReadCompleted += (o, a) =>
                {
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Response));
                    Response r = ser.ReadObject(a.Result) as Response;

                    if (r != null &&
                        r.ResourceSets != null &&
                        r.ResourceSets.Length > 0 &&
                        r.ResourceSets[0].Resources != null &&
                        r.ResourceSets[0].Resources.Length > 0)
                    {
                        Delegate foo = new Action(() => {
                            this.DataSourceJobListBox.DataContext = r.ResourceSets[0].Resources;
                        });

                        this.DataSourceJobListBox.Dispatcher.Invoke(foo, null);                    
                    }
                    else
                    {
                        MessageBox.Show("No recent data source jobs found.");
                    }
                };
                wc.OpenReadAsync(new Uri("http://spatial.virtualearth.net/REST/v1/Dataflows/ListJobs?key=" + BingMapsKeyTbx.Text));
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
        }
    }
}
